import variables from '@/styles/element-variables.scss'
import defaultSettings from '@/settings'
import { setCookieData, getCookieData, getLocalBoolData } from '@/utils/auth'

const { showSettings, tagsView, fixedHeader, sidebarLogo, showHeader } = defaultSettings

var localShowSettings = getCookieData('showSettings')
var localTagsView = getCookieData('tagsView')
var localSidebarLogo = getCookieData('sidebarLogo')
var localShowHeader = getCookieData('showHeader')

if (localShowSettings) {
  localShowSettings = getLocalBoolData('showSettings')
} else {
  localShowSettings = showSettings
}

if (localTagsView) {
  localTagsView = getLocalBoolData('tagsView')
} else {
  localTagsView = tagsView
}

if (localSidebarLogo) {
  localSidebarLogo = getLocalBoolData('sidebarLogo')
} else {
  localSidebarLogo = sidebarLogo
}

if (localShowHeader) {
  localShowHeader = getLocalBoolData('showHeader')
} else {
  localShowHeader = showHeader
}

const state = {
  theme: variables.theme,
  showSettings: localShowSettings,
  tagsView: localTagsView,
  fixedHeader: fixedHeader,
  sidebarLogo: localSidebarLogo,
  showHeader: localShowHeader
}

const mutations = {
  CHANGE_SETTING: (state, { key, value }) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      state[key] = value
      setCookieData(key, value)
    }
  },
  RESET_SETTING: (state, key) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      const value = getCookieData(key)
      if (value === 'true' || value === 'false') {
        state[key] = value === 'true'
      }
    }
  }
}

const actions = {
  changeSetting({ commit }, data) {
    commit('CHANGE_SETTING', data)
  },
  resetSetting({ commit }, data) {
    commit('RESET_SETTING', data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

